<script setup lang="ts">
import { useAppStore, useControllerStore } from '@/store';
import HomeRequest from '@/request/homeRequest';
import useToast from '@/hooks/useToast';
import { navigate } from '@/utils/navigate';

interface IState {
  show: boolean;
  data?: IProductInformation;
  skuData?: IObtainProductSpecificationsRes;
  selectSkuKey: string[];
  nums: number;
}

const store = useAppStore();
const controllerStore = useControllerStore();
const state = reactive<IState>({ show: false, selectSkuKey: [], nums: 1 });
const { showToast } = useToast();

watch(
  () => controllerStore.$state.skuSelectionPopup,
  (skuSelectionPopup) => {
    if (skuSelectionPopup && controllerStore.$state.productInformation) {
      state.data = controllerStore.$state.productInformation;
      fetchObtainProductSpecifications(state.data.goodsId);
    } else {
      state.show = false;
      state.data = undefined;
    }
  },
);

// 获得产品规格
const fetchObtainProductSpecifications = (goodsId: number) => {
  HomeRequest.ObtainProductSpecifications({ goodsId, hasLoading: true }).then((res) => {
    if (res.data.specList.length === 0) {
      showToast('该产品没有规格，请联系客服');
      controllerStore.$patch({ skuSelectionPopup: false, productInformation: undefined });
      return;
    }
    state.skuData = res.data;
    state.selectSkuKey = res.data.defaultVariant.sku.split(':');
    const key = state.selectSkuKey.join(',').replace(/,/g, ':');
    if (state.skuData.variantMap[key]) {
      state.data = { ...state.data!, salePrice: state.skuData.variantMap[key].salePrice, active: state.skuData.variantMap[key].active, sku: key, variantId: state.skuData.variantMap[key].variantId };
    }
    state.show = true;
  });
};

// 判断规格是否不可选
const hasSpecValDisable = (specVal: string, index: number) => {
  const keysArray: string[][] = Object.keys(state.skuData!.variantMap).map((key) => key.split(':'));
  return !keysArray.find((item) => item[index] === specVal);
};

// 规格选择
const handleSelectSpec = (specVal: string, index: number) => {
  state.selectSkuKey[index] = specVal;
  const key = state.selectSkuKey.join(',').replace(/,/g, ':');
  if (state.skuData && state.skuData.variantMap[key]) {
    state.data = { ...state.data!, salePrice: state.skuData.variantMap[key].salePrice, active: state.skuData.variantMap[key].active, sku: key, variantId: state.skuData.variantMap[key].variantId };
  }
};

// 加入购物车
const handleAddToShoppingCart = () => {
  if (state.data?.goodsType === 15 && store.$state.shoppingCart.length !== 0) {
    showToast('补差价产品不能和其他产品一起购买');
    return;
  }
  store.updateShoppingCartSku({ type: 'add', data: { ...state.data!, nums: state.nums } });
  controllerStore.$patch({ skuSelectionPopup: false, productInformation: undefined });
  showToast('加入购物车成功');
};

// 直接下单
const handleDirectOrderPlacement = () => {
  controllerStore.$patch({ skuSelectionPopup: false, productInformation: undefined });
  navigate({ url: `/subcontract/home/submitOrder/index?products=${encodeURIComponent(JSON.stringify({ ...state.data!, nums: state.nums }))}` });
};
</script>

<template>
  <van-popup :show="state.show" @close="() => controllerStore.$patch({ skuSelectionPopup: false, productInformation: undefined })">
    <view class="c-br c-pd w-screen flex justify-center" v-if="state.data">
      <view class="c-br bg-white c-pd w-full overflow-scroll max-h-500px">
        <view class="flex">
          <view class="w-80px h-80px c-br overflow-hidden">
            <image class="w-full h-full" :src="state.data.mainImage" lazy-load mode="aspectFill" />
          </view>
          <view class="pl-8px box-border overflow-hidden flex-1 flex flex-col justify-between">
            <view class="flex items-start">
              <view class="flex-1 c-text-ellipsis-2 w-full fw-bold">
                {{ state.data.name }}
              </view>
              <view v-if="state.data.visitFlag !== 0" class="ml-4px c-text-8 px-4px py-2px rounded-4px border-1px border-#999999 border-solid c-text-color-grey">服务上门</view>
            </view>
            <view v-if="state.data.introduce" class="w-fit mt-4px max-w-96% c-text-ellipsis rounded-4px text-#ec820d bg-#fdf7e3 px-4px py-1px c-text-10 block">
              {{ state.data.introduce }}
            </view>
            <view v-if="state.data.remark" class="w-fit mt-4px max-w-96% c-text-ellipsis rounded-4px text-white bg-#36af06d7 px-4px py-1px c-text-10 block">
              {{ state.data.remark }}
            </view>
          </view>
        </view>
        <view class="w-full mb-8px" v-for="(item, index) in state.skuData?.specList" :key="item.specId">
          <view class="c-text-14 my-8px fw-bold">{{ item.specName }}</view>
          <view class="grid grid-cols-3 gap-2">
            <template v-for="_item in item.specValList" :key="_item.specValId">
              <view v-if="hasSpecValDisable(_item.specVal, index)" class="flex justify-center items-center c-text-12 c-br border-1px border-solid py-4px text-#a8a7a7 border-#F1F1F1">大</view>
              <view v-else class="flex justify-center items-center c-text-12 c-br border-1px border-solid py-4px" :class="state.selectSkuKey[index] === _item.specVal ? 'bg-#FFFBF0 text-#ED8A2A border-#E0B83E' : 'border-#c5c1c1'" @click="handleSelectSpec(_item.specVal, index)">
                {{ _item.specVal }}
              </view>
            </template>
          </view>
        </view>
        <RenderProductDiscount :data="state.data" :count="state.nums - 1" :hasSku="true" />
        <view class="flex justify-between my-8px">
          <RenderProductPrice :data="state.data" :count="state.nums - 1" :hasSku="true" />
          <view class="flex items-center">
            <i class="i-gg:remove c-color c-text-16" @click="state.nums > 1 && state.nums--" />
            <text class="mx-8px fw-bold c-text-14">{{ state.nums }}</text>
            <i class="i-icon-park-solid:add-one c-color c-text-16" @click="() => (state.nums += 1)" />
          </view>
        </view>
        <view class="flex justify-center" v-if="state.data.goodsType !== 4">
          <view class="flex-1 c-bg-sec text-white py-8px text-align-center rounded-tl-12px rounded-bl-12px" @click="handleAddToShoppingCart">加入购物车</view>
          <view class="flex-1 c-bg py-8px text-align-center rounded-tr-12px rounded-br-12px" @click="handleDirectOrderPlacement">立即下单</view>
        </view>
        <view class="flex justify-center" v-else>
          <view class="flex-1 c-bg py-8px text-align-center c-br" @click="handleDirectOrderPlacement">立即下单</view>
        </view>
      </view>
    </view>
  </van-popup>
</template>
